package com.zlm.IO.ByteStream.ZipOutputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author 13026
 */
public class ZipOutputStream_demo2 {
    /*
     * ZipOutputStream
     * 压缩流
     * */
    public static void main(String[] args) throws IOException {
        // 1.创建一个File表示要解压的压缩包
        File src = new File("D:\\myProject\\javaTest\\oneModule\\src\\com\\zlm\\IO\\ByteStream\\ZipOutputStream\\FilesPackage");
        // 2.创建一个File表示解压的目的地
        // File dest = new File("D:\\myProject\\javaTest\\oneModule\\src\\com\\zlm\\IO\\ByteStream\\ZipOutputStream\\FilesPackage");
        File destParent = src.getParentFile();
        File dest = new File(destParent, src.getName() + ".zip");

        System.out.println(dest);

        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest));

        System.out.println(src.getName());
        toZip(src, zos, src.getName());

        zos.close();
    }

    public static void toZip(File src, ZipOutputStream zos, String name) throws IOException {
        File[] files = src.listFiles();
        if (files != null) {
            for (File file : files) {
                System.out.println(file.getName());
                if (file.isFile()) {
                    ZipEntry entry = new ZipEntry(name + "\\" + file.getName());
                    zos.putNextEntry(entry);
                    FileInputStream fis = new FileInputStream(file);
                    int b;
                    while ((b = fis.read()) != -1) {
                        zos.write(b);
                    }
                    zos.closeEntry();
                } else {
                    // 文件夹-递归
                    toZip(file, zos, name + "\\" + file.getName());
                }
            }
        }
    }
}
